package com.xm.controller.web;

import com.xm.pojo.Sysuser;
import com.xm.service.SysuserService;
import com.xm.util.JSONResult;
import com.xm.util.MD5;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @Author semstouch
 * @Date 2017/4/17
 **/
@Controller
@RequestMapping("/web")
public class LoginController {
    @Resource
    private SysuserService sysuserService;


    /**
     * 跳转到登陆页面方法
     * @return
     */
    @RequestMapping(value="/toLogin")
    public ModelAndView toLogin(){
        ModelAndView modelAndView=new ModelAndView("login");
        return modelAndView;
    }

    /**
     *登出跳转到登陆页面方法
     * @param request
     * @return
     */
    @RequestMapping(value = "/toLoginOut")
    public ModelAndView toLoginOut(HttpServletRequest request) {
        ModelAndView modelAndView=new ModelAndView("login");
        request.getSession().setAttribute("sysuser",null);
        return modelAndView;
    }

    /**
     *登陆方法
     * @param loginName
     * @param pwd
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult login(String loginName, String pwd,HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();

        Sysuser params= new Sysuser();
        params.setLoginName(loginName);
        params.setPwd(MD5.md5(pwd));
        Sysuser sysuser=sysuserService.selectByLogin(params);

        if(sysuser==null||sysuser.getRoleType().equals("2")){
            jsonResult.setSuccess(false);
            jsonResult.setMsg("帐号密码错误！");
            return jsonResult;
        }
        request.getSession().setAttribute("sysuser", sysuser);
        jsonResult.setData(sysuser);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     *登出方法
     * @param request
     * @return
     */
    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult loginOut(HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();
        request.getSession().setAttribute("sysuser",null);
        jsonResult.setSuccess(true);
        return jsonResult;
    }



    /**
     * 修改用户信息方法
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "/updateSysuser", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateEventInfo(Sysuser sysuser) throws Exception {
        JSONResult jsonResult = new JSONResult();
        sysuserService.update(sysuser);
        jsonResult.setSuccess(true);
        return jsonResult;
    }
}
